
import React, { useEffect, useState, useMemo, useReducer } from 'react';
import { List, InputItem, Toast, DatePicker, } from 'antd-mobile';
import { Radio } from 'antd';
import {
	Switch,
	Route,
	useHistory,
} from "react-router-dom";
import moment from 'moment';
import sdk from 'qcloud-iotexplorer-h5-panel-sdk';
const apirul = "https://iotapi.sziton.com/api/appapi/"
const imgrul = "https://iotapi.sziton.com/afile/J4GFRSTHQ4/"
// 当前时间
const current_time = (new Date()).valueOf()
const windowHeight = window.innerHeight || document.documentElement.clientHeight;
let myuserInfo = sdk.userInfo
// 用户信息卡片
function UserPage(props) {
	const history = useHistory()
	const [isinput, setisinput] = useState(false);
	// 三方用户数据
	const userinfo = props.userinfo
	const toInputPage = () => {
		// history.push("/InputUser",userinfo)
		setisinput(true)
	}
	return (
		<>{isinput ? <InputUser userinfo={userinfo} /> :
			<div className="InputUserPage pagebg" style={{ paddingBottom: "200px" }}>
				<Headinfo navtit={"我的资料"} />
				<div className="itemlist pdlr bdwhite">
					<div className="fl-rsbc bd1 pd">
						<div className="ilimg">性别</div>
						<div className="textcolor">
							{userinfo.sex != null ? userinfo.sex == 0 ? "女" : "男" : "暂无"}
						</div>
					</div>
					<div className="fl-rsbc bd1 pd">
						<div className="ilimg">身高</div>
						<div className="textcolor">{userinfo.height == null ? "0" : userinfo.height}(cm)</div>
					</div>
					<div className="fl-rsbc bd1 pd">
						<div className="ilimg">目标体重</div>
						<div className="textcolor">{userinfo.target_weight == null ? "00.00" : userinfo.target_weight}({userinfo.weight_unit == null ? "Kg" : userinfo.weight_unit})</div>
					</div>
					<div className="fl-rsbc bd1 pd">
						<div className="ilimg">生日</div>
						<div className="textcolor">{userinfo.birthday == null ? "暂无" : moment(parseInt(userinfo.birthday)).format('YYYY-MM-DD')}</div>
					</div>
					<div className="pdtb fl-cc">
						<div className="lfbtn-gr" onClick={toInputPage}>修改信息</div>
					</div>
				</div>
			</div>
		}</>
	)
}

// 输入卡片
export function InputUser(props) {
	const puinfo = props.userinfo
	const [isinput, setisinput] = useState(true);
	const minDate = new Date(1900, 1, 1, 0, 0, 0)
	const maxDate = new Date(2050, 12, 31, 0, 0, 0)

	const userData = {
		sex:puinfo.sex,
		birthday:puinfo.birthday,
		age:0,
		height:puinfo.height,
		target_weight:puinfo.target_weight
	};
	function userDatareducer(state, action) {
		switch (action.type) {
			case "birthday":
				console.log(action.value)
				let shengri = moment(action.value).valueOf()
				var sr = moment(action.value).format('YYYY/MM/DD')
				return {
					...state,
					birthday:shengri,
					age:matAge(sr),
				}
			case "height":
				return {
					...state,
					height:action.value,
				}
			case "target_weight":
				return {
					...state,
					target_weight:action.value
				}
			case "sex":
				return {
					...state,
					sex:parseInt(action.value),
				}
			default:
				return {
					sex:puinfo.sex,
					birthday:puinfo.birthday,
					age:0,
					height:puinfo.height,
					target_weight:puinfo.target_weight
				}
		}
	}
	const [userstate, userdispatch] = useReducer(userDatareducer, userData);
	const sexdata = [
		{ label: '男', value: 1 },
		{ label: '女', value: 0 }
	];
	const onChangerdo = (e) => {
		let value = e.target.value
		userdispatch({type:"sex",value})
	};
	const onChangesg = value => {
		userdispatch({type:"height",value})
	};
	const onChangetz = value => {
		userdispatch({type:"target_weight",value})
	};
	function onChangesr(value) {
		userdispatch({type:"birthday",value})
	}
	const dateFormat = 'YYYY/MM/DD';
	// const RadioItem = Radio.RadioItem;
	const updateThirdUser = () =>{
		// 获取三方用户，更新后数据
		console.log('开始更新三方用户数据')
		console.log(userstate)
		let age = forAge(parseInt(userstate.birthday),parseInt(current_time))
		if (parseInt(userstate.height) < 50 || parseInt(userstate.height) > 255 ){
			Toast.fail('身高数据有误！请确保身高在（50cm~255cm）之间！', 1)
		}else if (parseInt(age) < 10 || parseInt(age) > 100 ){
			Toast.fail('年龄数据有误！暂不支持该年龄段', 1) //请确保年龄在（10岁~100岁）之间！
		}else{
		var request = require('superAgent')
		request
			.post(apirul + 'updateThirdUser')
			.send({
				"productId": sdk.productId,
				"deviceName": sdk.deviceName,
				"sex": userstate.sex,
				"birthday": userstate.birthday,
				"target_weight": userstate.target_weight,
				"height": userstate.height,
				"wx_unionid": myuserInfo.UserID
			})
			.end(function (err, res) {
				if (res.body.code == 1) {
					// var bdinfo = JSON.parse(res.text).data.data
					console.log('更新数据如下：')
					console.log(res)
					Toast.success('更新成功！', 1, false, setisinput(false))
				} else {
					console.log('服务器出错')
					console.log(res)
				}
			})
		}
	}
	const checkdata = () =>{
		console.log("checkdata")
		console.log(userstate)
		// 1、年龄要在10-100岁以内（含10和100）
		// 2、身高要在50-255cm之间（含50,255）
		if (parseInt(userstate.height) > 50 && parseInt(userstate.height) < 255 ){
			return false
		}else if (parseInt(userstate.age) > 10 && parseInt(userstate.age) < 100 ){
			return false
		}else{
			return true
		}
	}
	useEffect(()=>{
		console.log("userstate.sex")
		console.log(userstate.sex)
		console.log(typeof(userstate.sex) )
		console.log(parseInt(userstate.sex) === 0)
	}, [])
	return (
		<>{isinput ?
			<div className="InputUserPage pagebg" style={{ paddingBottom: "200px" }}>
				<Headinfo navtit={"修改个人信息"} />
				<div className="itemlist pd bdwhite">
					<div className="fl-rsbc bd1 pd">
						<div className="ttitext">性别：</div>
						<div className="textcolor fl-rr">
							<Radio.Group onChange={onChangerdo} defaultValue={parseInt(userstate.sex)}>
								{sexdata.map(i => (
									<Radio key={i.value} value={i.value} defaultChecked={parseInt(userstate.sex) === (i.value)}>
										{i.label}
									</Radio>
								))}
							</Radio.Group>
						</div>
					</div>
					<div className="fl-rsbc bd1 ipuinput pdlr">
						<div className="ttitext">身高：</div>
						<div className="textcolor fl-rr">
							<InputItem
								placeholder="160"
								extra="CM"
								defaultValue={parseInt(userstate.height) === 0 ? 160 : userstate.height}
								onChange={onChangesg}
							></InputItem>
						</div>
					</div>
					<div className="fl-rsbc bd1 ipuinput pdlr">
						<div className="ttitext">目标体重：</div>
						<div className="textcolor fl-rr">
							<InputItem
								placeholder="60.00"
								extra="KG"
								defaultValue={parseInt(userstate.target_weight) === 0 || userstate.target_weight === undefined ? 60 : userstate.target_weight}
								onChange={onChangetz}
							></InputItem>
						</div>
					</div>
					<div className="bd1 ipuinput pdlr">
						<DatePicker
							mode="date"
							title="选择生日"
							extra={userstate.birthday != null ? moment(parseInt(userstate.birthday)).format('YYYY-MM-DD') : "1992-01-01"}
							minDate={minDate}
							maxDate={maxDate}
							onChange={onChangesr}
						>
							<List.Item arrow="horizontal">生日：</List.Item>
						</DatePicker>
					</div>
					<div className="pdtb fl-cc">
						<div className="lfbtn" onClick={updateThirdUser}>确认</div>
					</div>
				</div>
			</div>
			: <InputUserPage isinput={false} />}</>
	)
}
// 用户信息输入卡片
export function InputUserPage(props) {
	const isinput = props.isinput
	const [userinfo, setUserinfo] = useState({});
	useEffect(() => {
		// 获取用户信息
		const getLastUserData = () => {
			console.log()
			var request = require('superAgent')
			request
				.post(apirul + 'getlastuserinfo_tx')
				.send({
					"productId": sdk.productId,
					"deviceName": sdk.deviceName,
					"wx_unionid": myuserInfo.UserID,
					"username": myuserInfo.NickName,
					"userimg": myuserInfo.Avatar,
				})
				.end(function (err, res) {
					if (res.body.code == 1) {
						var JkcardUdata = res.body.data.third_user
						console.log('res', JkcardUdata)
						setUserinfo(JkcardUdata)
					} else {
						console.log('服务器' + res)
					}
				})
		}
		getLastUserData()
	}, [])
	console.log(isinput)
	return <>{isinput ? <InputUser userinfo={userinfo} /> : <UserPage userinfo={userinfo} />}</>
}
// 根据生日算年龄
const forAge=(bir,c_time)=>{
	var age = Math.ceil((c_time-bir)/31536000000);
	return age
}
// 根据生日算年龄
const matAge = (sr) => {
	var r = sr.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
	if (r == null) { console.log("日期为空！", r) };
	var d = new Date(r[1], r[3] - 1, r[4]);
	var Y = new Date().getFullYear();
	if (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]) {
		console.log("年龄   =   " + (Y - r[1]) + "   周岁");
		return Y - r[1];
	} else {
		return 0;
	}
}
function Headinfo(props) {
	const navtit = props.navtit
	return (
		<>
			<div className="headinfo fl-cc">
				<div className="navtit">{navtit}</div>
				<div className="bigheadimg mgb"><img src={myuserInfo.Avatar == "" ? imgrul + "headimg.png" : myuserInfo.Avatar} /></div>
				<div className="mgb">{myuserInfo.NickName}</div>
			</div>
		</>
	)
}